package cn.wolfcode.service.impl;

import cn.wolfcode.domain.Destination;
import cn.wolfcode.domain.Region;
import cn.wolfcode.query.QueryObject;
import cn.wolfcode.repsitory.RegionRepsitory;
import cn.wolfcode.service.IRegionService;
import org.springframework.data.domain.*;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * @Description: Region业务逻辑实现类
 * @Author: 伍家钰
 * @Date: 2020/8/7 16:20
 * @Version: 1.0
 */
@Service
public class RegionServiceImpl implements IRegionService {
    @Resource
    private RegionRepsitory regionRepsitory;
    @Resource
    private MongoTemplate mongoTemplate;

    @Override

    public void save(Region region) {
        // 将id设置成空,否则传入保存的是"",导致自动生成的id不会保存进来
        region.setId(null);
        regionRepsitory.save(region);
    }

    @Override
    public void delete(String id) {
        regionRepsitory.deleteById(id);
    }

    @Override
    public void update(Region region) {
        regionRepsitory.save(region);
    }

    @Override
    public Region get(String id) {
        return regionRepsitory.findById(id).orElse(null);
    }

    @Override
    public List<Region> list() {
        return regionRepsitory.findAll();
    }

    @Override
    public Page<Region> query(QueryObject qo) {
        Query query = new Query();
        // 总数据
        long total = mongoTemplate.count(query, Region.class);
        if (total == 0) {
            // 如果返回null会报错
            return Page.empty();
        }

        // 当前页显示的数据,Pageable是PageRequest的父接口的父接口
        Pageable pageable = PageRequest.of(qo.getCurrentPage() - 1, qo.getPageSize(), Sort.Direction.ASC, "_id");
        query.with(pageable);
        List<Region> list = mongoTemplate.find(query, Region.class);
        return new PageImpl<>(list, pageable, total);
    }

    @Override
    public void saveOrUpdate(Region region) {
        if (region.getId() != null) {
            // 更新
            this.update(region);
        } else {
            // 添加
            this.save(region);
        }
    }

    @Override
    public void changeHotValue(int hot, String id) {
        //------------------- 局部更新 --------------------
        Query query = new Query();
        // 2.拼接查询条件
        Criteria criteria = Criteria.where("_id").is(id);
        query.addCriteria(criteria);
        // 3.创建一个新对象
        Update update = new Update();
        // 4.给update对象设置属性
        update.set("ishot", hot);
        // 5.执行语句,参数1:语句条件,参数2:要跟新的数据对象,参数3:返回类型
        mongoTemplate.updateMulti(query, update, Region.class);
    }

    @Override
    public List<Region> hotRegion() {
        return regionRepsitory.findByIshotOrderBySequence(Region.STATE_HOT);
    }

}
